package keye.document_manage.util;

import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class MultipleDataSource extends AbstractRoutingDataSource{

	public static final String MYSQL = "mySqlDataSource";
	public static final String SQLSERVER = "sqlServerDataSource";
	public static final String SQLITE = "sqliteDataSource";
	private static Dialect dialect =null;
	private static final ThreadLocal<String> dataSourceKey = new InheritableThreadLocal<String>();
	private static final List<Dialect> dialects = new ArrayList<Dialect>();

	static {
		init();
	}
	
	public static Dialect getDialect(String sqlType){
		switch(sqlType){
		case MultipleDataSource.MYSQL : return dialects.get(0);
		case MultipleDataSource.SQLSERVER : return dialects.get(1);
		case MultipleDataSource.SQLITE : return dialects.get(2);
		default : return dialects.get(0);
		}
	}
	
	private static void init(){
		dialects.add(0, new MySqlDialect());
		dialects.add(1, new SqlServerDialect());
		dialects.add(2, new SqliteDialect());
	}
	
	public static void setDatasourceKey(String dataSource) {
		dataSourceKey.set(dataSource);
	}
	
	@Override
	protected Object determineCurrentLookupKey() {
		return dataSourceKey.get();
	}

	public static void setDialect(Dialect dia){
		dialect = dia;
	}
	
	public synchronized static void setDialect(String type){
		dialect = getDialect(type);
	}
	
	public static Dialect getDialect(){
		return dialect;
	}
}
